<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="项目文件管理" data-page-identification="t_55vxrgdufp">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_k0esapxuq8 自定义模板_m3xmy0hu1v -->

            <!--          选择下载文件的类型-->
            <a-modal
                v-model:visible="fileState.downLoadTypeVisible"
                title="下载全部附件"
                centered
                :mask-closable="false"
                :keyboard="false"
                @ok="handleDownAllTask"
                @cancel="cancelDownAll"
                :ok-button-props="{ loading: fileState.downLoadLoading }"
            >
                <a-checkbox-group v-model:value="fileState.downLoadTypeList">
                    <a-checkbox value="附件">附件</a-checkbox>
                    <a-checkbox value="附件模板">附件模板</a-checkbox>
                </a-checkbox-group>
            </a-modal>
            <!--          选择下载文件的类型-->
            <!--                  上传附件-->
            <a-modal
                :visible="fileState.uploadVisible"
                title="上传附件"
                centered
                width="800px"
                destroy-on-close
                :body-style="{
                    paddingBottom: 0
                }"
                :ok-button-props="{ loading: fileState.uploadLoading }"
                @ok="handleConfirmFileNew"
                @cancel="handleCancelFileNew"
            >
                <div class="file-modal-div">
                    <a-form :model="fileState.formModelNew" ref="fileRefNew">
                        <a-row>
                            <a-col :span="12">
                                <a-form-item label="项目阶段名称">
                                    <a-input disabled v-model:value="fileState.formModelNew.milepostName" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="项目阶段序号">
                                    <a-input disabled v-model:value="fileState.formModelNew.serialNumber" />
                                </a-form-item>
                            </a-col>

                            <!--                            <a-col :span="24">-->
                            <!--                                <a-form-item label="文件上传清单">-->
                            <!--                                    <div class="file-description">-->
                            <!--                                        <a-textarea v-model:value="fileState.formModelNew.fileDescription" />-->
                            <!--                                    </div>-->
                            <!--                                </a-form-item>-->
                            <!--                            </a-col>-->

                            <a-col>
                                <a-form-item label="附件上传">
                                    <a-upload
                                        :file-list="fileState.formModelNew.fileList"
                                        :before-upload="handlerFileUploadNew"
                                        @remove="handleFileRemoveNew"
                                        multiple
                                        accept=".xlsx,.ppt,.pdf,.PDF, image/*, .docx, .rp, .xls"
                                    >
                                        <a-button type="primary">
                                            <upload-outlined />
                                            上传
                                        </a-button>
                                    </a-upload>
                                    <span>支持格式：image/*,.xlsx,.xls,.docx,.rp,.ppt,.pptx,.pdf</span>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
            <!--                  上传附件-->
            <a-modal
                :visible="fileState.visible"
                title="新建任务文件"
                centered
                width="800px"
                destroy-on-close
                :body-style="{
                    paddingBottom: 0
                }"
                :ok-button-props="{ loading: fileState.okLoading }"
                @ok="handleConfirmFile"
                @cancel="handleCancelFile"
            >
                <div class="file-modal-div">
                    <a-form :model="fileState.formModel" ref="fileRef">
                        <a-row>
                            <a-col :span="12">
                                <a-form-item
                                    label="项目阶段"
                                    :rules="[{ required: true, message: '请选择项目阶段', trigger: 'blur' }]"
                                    name="milepostName"
                                >
                                    <a-select
                                        show-search
                                        :field-names="{ label: 'milepostName', value: 'milepostId' }"
                                        :filter-option="
                                            (input, option) => {
                                                return (
                                                    option.milepostName.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                )
                                            }
                                        "
                                        :options="fileState.milepostList"
                                        @focus="getFileMilepost"
                                        v-model:value="fileState.formModel.milepostName"
                                        @change="
                                            () => {
                                                fileState.formModel.taskId = undefined
                                            }
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item
                                    label="任务"
                                    :rules="[{ required: true, message: '请选择任务', trigger: 'blur' }]"
                                    name="taskId"
                                >
                                    <a-select
                                        show-search
                                        :options="fileState.taskList"
                                        v-model:value="fileState.formModel.taskId"
                                        :filter-option="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        @focus="getFileTaskList"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col>
                                <a-form-item
                                    label="附件上传"
                                    :rules="[{ required: true, message: '请上传附件', trigger: 'blur' }]"
                                    name="fileList"
                                >
                                    <a-upload
                                        :file-list="fileState.formModel.fileList"
                                        :before-upload="handlerFileUpload"
                                        @remove="handleFileRemove"
                                        accept=".xlsx,.ppt,.pdf,.PDF, image/*, .docx, .rp, .xls"
                                    >
                                        <a-button type="primary">
                                            <upload-outlined />
                                            上传
                                        </a-button>
                                    </a-upload>
                                    <span>支持格式：image/*,.xlsx,.xls,.docx,.rp,.ppt,.pptx,.pdf</span>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
            <!--          删除文件-->
            <a-modal
                :visible="fileState.deleteVisible"
                title="删除文件"
                @ok="confirmDeleteFile"
                @cancel="fileState.deleteVisible = false"
                centered
            >
                <p>确认删除该文件？</p>
                <p> 提交后进入审批流程，删除后项目</p>
                <p>相关展示位置将一并删除和取消展示</p>
            </a-modal>
            <!--          删除文件-->
            <div class="file-body">
                <div class="search-top" v-if="fileState.searchForm.radioValue === '任务文件'">
                    <a-form>
                        <a-row style="height: 40px" :gutter="24">
                            <a-col :span="6">
                                <a-form-item label="文件名称">
                                    <a-input v-model:value="fileState.searchForm.fileName" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="提交日期">
                                    <a-range-picker
                                        v-model:value="fileState.searchForm.dateList"
                                        valueFormat="YYYY-MM-DD"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="4">
                                <a-space>
                                    <a-button type="primary" @click="getFileData"> 查询</a-button>
                                    <a-button class="mr16" @click="resetFileData">重置</a-button>
                                </a-space>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <div class="file-table-box">
                    <div class="file-table-radio">
                        <a-radio-group
                            v-model:value="fileState.searchForm.radioValue"
                            button-style="solid"
                            @change="getFileData"
                        >
                            <a-radio-button value="项目信息">项目信息</a-radio-button>
                            <a-radio-button value="任务文件">任务文件</a-radio-button>
                        </a-radio-group>
                        <a-space>
                            <!--                            <a-button-->
                            <!--                                type="primary"-->
                            <!--                                v-if="fileState.searchForm.radioValue === '任务文件'"-->
                            <!--                                @click="handleAddFile"-->
                            <!--                                v-permission="'3000000879_vid_ehymarwuhz'"-->
                            <!--                                >新建</a-button-->
                            <!--                            >-->
                            <a-button
                                type="primary"
                                v-permission="'3000000879_vid_lj7j8ss759'"
                                v-if="fileState.searchForm.radioValue === '项目信息'"
                                @click="handleDownAll"
                                :loading="fileState.downLoadLoading"
                                >下载全部附件</a-button
                            >
                            <a-button
                                v-else
                                type="primary"
                                v-permission="'3000000879_vid_lj7j8ss759'"
                                @click="handleShowDownLoadType"
                                :loading="fileState.downLoadLoading"
                                >下载全部附件</a-button
                            >
                        </a-space>
                    </div>
                    <a-table
                        :scroll="{
                            x: 'max-content',
                            y:
                                fileState.searchForm.radioValue === '任务文件'
                                    ? fileState.tableHeight
                                    : fileState.tableHeight + 60
                        }"
                        v-if="fileState.searchForm.radioValue === '项目信息'"
                        :columns="fileColumns"
                        bordered
                        :data-source="fileState.dataSource"
                        :pagination="false"
                        :loading="fileState.tableLoading"
                    >
                        <template #bodyCell="{ column, record, text }">
                            <template v-if="column.dataIndex === 'file'">
                                <!--                                  预览/下载-->
                                <div v-for="(item, index) in record.fileList" :key="index">
                                    <a
                                        style="
                                            overflow: hidden;
                                            white-space: nowrap;
                                            text-overflow: ellipsis;
                                            display: block;
                                        "
                                        :title="item.name"
                                        @click="handleDownFile(item)"
                                    >
                                        {{ item.name }}
                                    </a>
                                    <!--                                    <a-dropdown>-->
                                    <!--                                        <span-->
                                    <!--                                            style="-->
                                    <!--                                                overflow: hidden;-->
                                    <!--                                                white-space: nowrap;-->
                                    <!--                                                text-overflow: ellipsis;-->
                                    <!--                                                display: block;-->
                                    <!--                                            "-->
                                    <!--                                            :title="item.name"-->
                                    <!--                                            @click="handleDownFile(item)"-->
                                    <!--                                        >-->
                                    <!--                                            {{ item.name }}-->
                                    <!--                                        </span>-->
                                    <!--                                        &lt;!&ndash;                                        <template #overlay>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                            <a-menu>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                                <a-menu-item>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                                    <a-button style="width: 100%" type="link" size="small" :disabled="!item.type.startsWith('image')" @click="previewAttachment(item)">预览</a-button>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                                </a-menu-item>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                                <a-menu-item>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                                    <a-button style="width: 100%" type="link" size="small" @click="handleDownFile(item)">下载</a-button>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                                </a-menu-item>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                            </a-menu>&ndash;&gt;-->
                                    <!--                                        &lt;!&ndash;                                        </template>&ndash;&gt;-->
                                    <!--                                    </a-dropdown>-->
                                </div>
                                <!--                                  预览/下载-->
                            </template>
                            <!--                            <template v-if="column.dataIndex === 'fileName'">-->
                            <!--                                <a-dropdown>-->
                            <!--                                    <span-->
                            <!--                                        style="-->
                            <!--                                            overflow: hidden;-->
                            <!--                                            white-space: nowrap;-->
                            <!--                                            text-overflow: ellipsis;-->
                            <!--                                            display: block;-->
                            <!--                                            cursor: pointer;-->
                            <!--                                        "-->
                            <!--                                        :title="record.fileList[0].name"-->
                            <!--                                    >-->
                            <!--                                        {{ record.fileList[0].name }}-->
                            <!--                                    </span>-->
                            <!--                                    <template #overlay>-->
                            <!--                                        <a-menu>-->
                            <!--                                            <a-menu-item>-->
                            <!--                                                <a-button-->
                            <!--                                                    style="width: 100%"-->
                            <!--                                                    type="link"-->
                            <!--                                                    size="small"-->
                            <!--                                                    @click="handleDownFile(record.fileList[0])"-->
                            <!--                                                    >下载</a-button-->
                            <!--                                                >-->
                            <!--                                            </a-menu-item>-->
                            <!--                                        </a-menu>-->
                            <!--                                    </template>-->
                            <!--                                </a-dropdown>-->
                            <!--                            </template>-->
                            <template v-if="column.dataIndex === 'opration'">
                                <a-space>
                                    <!--                                    <a-button type="link" @click="handleDeleteFile(record)">删除</a-button>-->
                                    <a-button
                                        type="link"
                                        :disabled="!record.operateFlag"
                                        @click="handleShowUpload(record)"
                                        >上传附件</a-button
                                    >
                                </a-space>
                            </template>
                        </template>
                    </a-table>
                    <a-table
                        v-else
                        :scroll="{ x: '1300px', y: fileState.tableHeight }"
                        :columns="fileTaskColumns"
                        bordered
                        :data-source="fileState.taskDataSource"
                        :loading="fileState.tableLoading"
                        :pagination="false"
                    >
                        <template #bodyCell="{ column, record, text }">
                            <template v-if="column.dataIndex === 'fileTemplateList'">
                                <a
                                    v-for="(item, index) in record.fileTemplateList"
                                    :key="index"
                                    href="javascript:"
                                    style="
                                        overflow: hidden;
                                        white-space: nowrap;
                                        text-overflow: ellipsis;
                                        display: block;
                                        cursor: pointer;
                                    "
                                    @click="handleDownFile(item)"
                                    :class="['block', index > 2 && !record.attachmentShowAll ? 'hide' : '']"
                                >
                                    {{ item.name }}
                                </a>
                            </template>
                            <template v-if="column.dataIndex === 'fileName'">
                                <a
                                    style="
                                        overflow: hidden;
                                        white-space: nowrap;
                                        text-overflow: ellipsis;
                                        display: block;
                                        cursor: pointer;
                                    "
                                    @click="handleDownFile(record.fileList[0])"
                                    :title="record.fileList[0].name"
                                >
                                    {{ record.fileList[0].name }}
                                </a>
                            </template>
                            <!--                            <template v-if="column.dataIndex === 'opration'">-->
                            <!--                                <a-space>-->
                            <!--                                    <a-button-->
                            <!--                                        type="link"-->
                            <!--                                        :disabled="!record.operateFlag"-->
                            <!--                                        @click="handleDeleteFile(record)"-->
                            <!--                                        >删除</a-button-->
                            <!--                                    >-->
                            <!--                                </a-space>-->
                            <!--                            </template>-->
                            <template v-if="column.dataIndex === 'milepostName'">
                                {{ record.serialNumber }} {{ text }}
                            </template>
                            <template v-if="column.dataIndex === 'taskName'">
                                {{ record.taskNumber }} {{ text }}
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>
            <!-- end vid_k0esapxuq8 自定义模板_m3xmy0hu1v -->
            <!-- begin vid_g5be9r1re4 容器_zkfelfkba5 -->
            <al-box v-if="false" class="vid_g5be9r1re4">
                <!-- begin vid_lj7j8ss759 项目文件管理-下载全部附件 -->
                <a-button v-permission="'3000000879_vid_lj7j8ss759'" class="vid_lj7j8ss759">
                    项目文件管理-下载全部附件
                </a-button>
                <!-- end vid_lj7j8ss759 项目文件管理-下载全部附件 -->
                <!-- begin vid_ehymarwuhz 项目文件管理-新建任务附件 -->
                <a-button v-permission="'3000000879_vid_ehymarwuhz'" class="vid_ehymarwuhz">
                    项目文件管理-新建任务附件
                </a-button>
                <!-- end vid_ehymarwuhz 项目文件管理-新建任务附件 -->
            </al-box>
            <!-- end vid_g5be9r1re4 容器_zkfelfkba5 -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'projectId': {
            type: [String, Number],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    const { projectId } = props
    const useProjectId = ref()
    import { watchEffect } from 'vue'
    watchEffect(() => {
        if (props.projectId) {
            setTimeout(() => {
                useProjectId.value = props.projectId
                getFileData()
            }, 500)
        }
    })
    // 文件管理
    const fileState = reactive({
        searchForm: {
            fileName: undefined,
            dateList: [],
            radioValue: '项目信息'
        },
        tableLoading: false,
        okLoading: false,
        uploadLoading: false,
        dataSource: [],
        taskList: [],
        milepostList: [],
        taskDataSource: [],
        visible: false,
        uploadVisible: false,
        formModel: {
            fileType: '任务文件',
            description: undefined,
            fileList: [],
            milepostName: undefined,
            taskId: undefined
        },
        formModelNew: {
            fileDescription: undefined,
            fileList: [],
            milepostName: undefined,
          milepostId: undefined,
            projectId: undefined,
            id: undefined,
            serialNumber: undefined
        },
        deleteVisible: false,
        tableHeight: 600,
        downLoadTypeVisible: false,
        downLoadLoading: false,
        downLoadTypeList: []
    })
    const fileColumns = ref([
        {
            title: '序号',
            dataIndex: 'rowNo',
            align: 'center',
            width: 100
        },
        {
            title: '项目阶段',
            dataIndex: 'milepostName',
            align: 'center',
            width: 200,
            ellipsis: true,
            customCell: ({ milepostRowSpan }) => {
                return {
                    rowSpan: milepostRowSpan
                }
            }
        },

        // {
        //     title: '文件上传清单',
        //     dataIndex: 'fileDescription',
        //     align: 'center',
        //     width: 300,
        //     customCell: ({ milepostRowSpan }) => {
        //         return {
        //             style: {
        //                 fontStyle: 'italic',
        //                 color: '#A3A3A3'
        //             }
        //         }
        //     }
        // },
        {
            title: '附件',
            dataIndex: 'file',
            align: 'center',
            width: 300
        },
        {
            title: '操作',
            fixed: 'right',
            dataIndex: 'opration',
            align: 'center',
            width: 100
        }
    ])
    const fileTaskColumns = ref([
        {
            title: '项目阶段',
            dataIndex: 'stageClassify',
            align: 'center',
            fixed: 'left',
            ellipsis: true,
            width: 150,
            customCell: ({ stageClassifyRowSpan }) => {
                return {
                    rowSpan: stageClassifyRowSpan
                }
            }
        },
        {
            title: '里程碑项目阶段',
            dataIndex: 'milepostName',
            align: 'center',
            width: 150,
            ellipsis: true,
            fixed: 'left',
            customCell: ({ milepostRowSpan }) => {
                return {
                    rowSpan: milepostRowSpan
                }
            }
        },

        {
            title: '任务名称',
            dataIndex: 'taskName',
            align: 'center',
            width: 100,
            fixed: 'left',
            ellipsis: true,
            customCell: ({ taskRowSpan }) => {
                return {
                    rowSpan: taskRowSpan
                }
            }
        },
        {
            title: '附件模板',
            dataIndex: 'fileTemplateList',
            width: 300,
            align: 'center',
            customCell: ({ fileRowSpan }) => {
                return {
                    rowSpan: fileRowSpan
                }
            }
        },
        {
            title: '文件名称',
            dataIndex: 'fileName',
            width: 300,
            align: 'center'
        },
        {
            title: '提交时间',
            dataIndex: 'submissionTime',
            align: 'center',
            width: 200
        },
        {
            title: '提交人',
            dataIndex: 'submitter',
            align: 'center',
            width: 100
        }
    ])

    function handleDownFile(item) {
        const props = { ...item }
        let xhr = new XMLHttpRequest()
        xhr.open('GET', props.url, true)
        xhr.responseType = 'blob'
        xhr.onload = function () {
            if (xhr.status === 200) {
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(xhr.response, props.name)
                } else {
                    let link = document.createElement('a')
                    let body = document.querySelector('body')
                    link.href = window.URL.createObjectURL(xhr.response)
                    link.download = props.name
                    // fix Firefox
                    link.style.display = 'none'
                    body.appendChild(link)
                    link.click()
                    body.removeChild(link)
                    window.URL.revokeObjectURL(link.href)
                }
            }
        }
        xhr.send()
    }

    function handlerFileUpload(file) {
        const data = new FormData()
        data.append('file', file)
        post('/file-storage/api/v1/file/upload', data)
            .then(({ data: { fullUrl } }) => {
                if (data) {
                    fileState.formModel.fileList = [
                        ...fileState.formModel.fileList,
                        {
                            uid: file.uid,
                            lastModified: file.lastModified,
                            name: file.name,
                            size: file.size,
                            type: file.type,
                            status: 'done',
                            url: fullUrl
                        }
                    ]
                }
            })
            .finally(() => {})
        return false
    }

    function handleFileRemove(file) {
        fileState.formModel.fileList = fileState.formModel.fileList.filter(item => item.uid !== file.uid)
    }

    function handleAddFile() {
        fileState.visible = true
    }

    const fileRef = ref(null)

    function handleConfirmFile() {
        fileRef.value.validate().then(() => {
            fileState.okLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/file_manage/add', {
                projectId: useProjectId.value,
                ...fileState.formModel
            })
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)
                    handleCancelFile()
                    getFileData()
                })
                .finally(() => {
                    fileState.okLoading = false
                })
        })
    }

    function handleCancelFile() {
        fileState.formModel = {
            fileType: '任务文件',
            description: undefined,
            fileList: [],
            milepostName: undefined,
            taskId: undefined
        }
        fileState.visible = false
    }

    function changeFileType() {
        if (fileState.formModel.fileType === '项目信息') {
            fileState.formModel.milepostName = fileState.formModel.taskId = undefined
        } else {
            fileState.formModel.description = undefined
        }
    }

    function getFileData() {
        if (fileState.searchForm.radioValue === '项目信息') {
            fileState.tableLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/file_manage/project_file_list', {
                projectId: useProjectId.value,
                fileName: fileState.searchForm.fileName,
                dateList: fileState.searchForm.dateList
            })
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    fileState.dataSource = data.data
                })
                .finally(() => {
                    fileState.tableLoading = false
                })
        } else {
            fileState.searchForm.fileName = undefined
            fileState.searchForm.dateList = []
            fileState.tableLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/file_manage/task_file_list', {
                projectId: useProjectId.value,
                fileName: fileState.searchForm.fileName,
                dateList: fileState.searchForm.dateList
            })
                .then(data => {
                    fileState.tableLoading = true
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    fileState.taskDataSource = groupFileData(data.data)
                })
                .finally(() => {
                    fileState.tableLoading = false
                })
        }
    }

    function resetFileData() {
        fileState.searchForm.fileName = undefined
        fileState.searchForm.dateList = []
        getFileData()
    }

    function groupFileData(data) {
        let currentTaskName = ''
        let currentMilepostName = ''
        let currentStageClassify = ''
        let taskRowSpan = 0
        let milepostRowSpan = 0
        let stageClassifyRowSpan = 0
        let currentFileList = '' // 获取文件列表
        let fileRowSpan = 0
        return data.map((item, index) => {
            // 如果 taskName 变化，重置 taskRowSpan，并计算新的 rowSpan
            if (currentTaskName !== item.taskName) {
                currentTaskName = item.taskName
                taskRowSpan = 1

                // 计算相同 taskName 的 rowSpan
                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].taskName === item.taskName) {
                        taskRowSpan++
                    } else {
                        break
                    }
                }
                item.taskRowSpan = taskRowSpan
            } else {
                item.taskRowSpan = 0
            }

            // 如果 milepostName 变化，重置 milepostRowSpan，并计算新的 rowSpan
            if (currentMilepostName !== item.milepostName) {
                currentMilepostName = item.milepostName
                milepostRowSpan = 1

                // 计算相同 milepostName 的 rowSpan
                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].milepostName === item.milepostName) {
                        milepostRowSpan++
                    } else {
                        break
                    }
                }
                item.milepostRowSpan = milepostRowSpan
            } else {
                item.milepostRowSpan = 0
            }
            // 如果 currentStageClassify 变化，重置 currentStageClassify，并计算新的 rowSpan
            if (currentStageClassify !== item.stageClassify) {
                currentStageClassify = item.stageClassify
                stageClassifyRowSpan = 1

                // 计算相同 milepostName 的 rowSpan
                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].stageClassify === item.stageClassify) {
                        stageClassifyRowSpan++
                    } else {
                        break
                    }
                }
                item.stageClassifyRowSpan = stageClassifyRowSpan
            } else {
                item.stageClassifyRowSpan = 0
            }
            if (currentFileList !== item.fileTemplate) {
                currentFileList = item.fileTemplate
                fileRowSpan = 1

                // 计算相同 milepostName 的 rowSpan
                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].fileTemplate === item.fileTemplate) {
                        fileRowSpan++
                    } else {
                        break
                    }
                }
                item.fileRowSpan = fileRowSpan
            } else {
                item.fileRowSpan = 0
            }
            return item
        })
    }

    const currentFile = ref({})

    function handleDeleteFile(record) {
        currentFile.value = record
        fileState.deleteVisible = true
    }

    function confirmDeleteFile() {
        const params = {
            id: undefined, //项目删除传
            fileName: undefined,
            taskId: undefined
        }
        if (fileState.searchForm.radioValue === '项目信息') {
            params.id = currentFile.value.id
        } else {
            params.id = currentFile.value.id
            params.taskId = currentFile.value.taskId
            params.fileName = currentFile.value.fileName
        }
        post('/solution-ppm/api/v2/built-in-system-ppm/file_manage/remove', params).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            fileState.deleteVisible = false
            getFileData()
        })
    }

    function getFileMilepost() {
        get(`/solution-ppm/api/v2/built-in-system-ppm/file_manage/milepost/${useProjectId.value} `).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            fileState.milepostList = data.data
        })
    }

    function getFileTaskList() {
        // setTimeout(()=>{
        //   fileState.taskList = [{ taskId: '1', taskName: '测试任务' }]
        //
        // },2000)
        // return;
        if (!fileState.formModel.milepostName) {
            return
        }
        get(`/solution-ppm/api/v2/built-in-system-ppm/file_manage/task/${fileState.formModel.milepostName}`).then(
            data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                fileState.taskList = data.data.map(item => {
                    return {
                        label: item.taskName,
                        value: item.taskId
                    }
                })
                console.log(data.data)
            }
        )
    }
    function handleShowUpload(record) {
        const item = cloneDeep(record)
        Object.assign(fileState.formModelNew, item)
        fileState.uploadVisible = true
    }
    function handleConfirmFileNew() {
        fileState.uploadLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/file_manage/milepost', fileState.formModelNew)
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)
                handleCancelFileNew()
                getFileData()
            })
            .finally(() => {
                fileState.uploadLoading = false
            })
    }

    function handleCancelFileNew() {
        fileState.formModelNew = {
            id: undefined,
            fileDescription: undefined,
            fileList: [],
            milepostName: undefined,
            serialNumber: undefined
        }
        fileState.uploadVisible = false
    }
    function handlerFileUploadNew(file) {
        const data = new FormData()
        data.append('file', file)
        post('/file-storage/api/v1/file/upload', data)
            .then(({ data: { fullUrl } }) => {
                if (data) {
                    fileState.formModelNew.fileList = [
                        ...fileState.formModelNew.fileList,
                        {
                            uid: file.uid,
                            lastModified: file.lastModified,
                            name: file.name,
                            size: file.size,
                            type: file.type,
                            status: 'done',
                            url: fullUrl
                        }
                    ]
                }
            })
            .finally(() => {})
        return false
    }

    function handleFileRemoveNew(file) {
        fileState.formModelNew.fileList = fileState.formModelNew.fileList.filter(item => item.uid !== file.uid)
    }
    function handleDownAll() {
        fileState.downLoadLoading = true
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/file_manage/milepost/download/${useProjectId.value}`,
            fileState.downLoadTypeList,
            {
                responseType: 'blob'
            }
        ).then(res => {
            if (res.type === 'application/octet-stream') {
                downloadZip(res, '全部附件.zip')
                fileState.downLoadLoading = false
                fileState.downLoadTypeVisible = false
            } else {
                message.info('项目没有附件')
                fileState.downLoadLoading = false
                fileState.downLoadTypeVisible = false
            }
        })
    }
    function handleDownAllTask() {
        if (fileState.downLoadTypeList.length == 0) {
            message.info('请选择下载附件范围')
            return
        }
        fileState.downLoadLoading = true
        post(
            `/solution-ppm/api/v2/built-in-system-ppm/file_manage/task/download/${useProjectId.value}`,
            fileState.downLoadTypeList,
            {
                responseType: 'blob'
            }
        ).then(res => {
            if (res.type === 'application/octet-stream') {
                downloadZip(res, '全部附件.zip')
                fileState.downLoadLoading = false
                fileState.downLoadTypeVisible = false
            } else {
                message.info('项目没有附件')
                fileState.downLoadLoading = false
                fileState.downLoadTypeVisible = false
            }
        })
    }
    function handleShowDownLoadType() {
        fileState.downLoadTypeVisible = true
    }
    function cancelDownAll() {
        fileState.downLoadTypeVisible = false
        fileState.downLoadTypeList = []
    }
    function downloadZip(response, name) {
        const blob = new Blob([response], { type: 'application/zip;charset=utf-8' })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = name // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click()
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
        return href
    }

    // 文件管理
    //     富文本设置
    import { nextTick } from 'vue'
    const headerOffset = ref(160)
    const calcTableHeight = () => {
        fileState.tableHeight = window.innerHeight - 180 - headerOffset.value
    }

    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })

    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .vid_g5be9r1re4 {
        padding-top: 24px;
        padding-bottom: 24px;
        background-color: #fb0808;
    }
    .vid_lj7j8ss759 {
        box-shadow: 0px 0px 0px 0px;
    }

    /*文件管理*/
    /*样式*/
    .file-body {
        height: 100%;
        background-color: #fff;
    }

    .file-body .search-top {
        padding: 10px 24px;
        background: #fff;
        margin-bottom: 14px;
        border-bottom: 1px solid #d9d9d9;
    }

    .file-table-box:deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #3875ff;
        color: #fff;
        font-weight: 600;
        padding: 8px 16px;
        border-right: 1px solid #d9d9d9 !important;
        position: relative;
    }

    .file-table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }

    .file-table-radio {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
    }

    .file-modal-div :deep(.ant3-form-item-label) {
        width: 120px;
    }
    .file-description :deep(.ant3-input) {
        color: #a3a3a3 !important;
    }
    /*样式*/
    /*文件管理*/
</style>
